﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lists;
using Vouchers;
using AccountingLibs;
using System.Data.SqlClient;
using GuiUtilities;

namespace BarCodeChuan
{
    public partial class FrmBarCode : BasicForms.FrmBase
    {
        public double cPrinterWidth, cPrinterHeight;
        int ColsPerPage, RowsPerPage;
        public void GetValue(ref int SoCot, ref int SoDong,ref double Widths, ref double Hegihts )
        { 
            SoCot=ColsPerPage;
            SoDong=RowsPerPage;
            Widths=cPrinterWidth;
            Hegihts = cPrinterHeight;
        }
        public FrmBarCode()
        {
            InitializeComponent();
        }
        private void FrmMain_Load(object sender, EventArgs e)
        {
            #region cmbDoiTuong
            cmbDoiTuong.DataSource = DanhMucDoiTuongNghiepVu.GetDanhMucKhachHang().DataView;
            cmbDoiTuong.DisplayColumn = "Ten";
            cmbDoiTuong.ValueColumn = "ID";
            cmbDoiTuong.AddVisibleColumn("Ma", "Mã");
            cmbDoiTuong.AddVisibleColumn("Ten", "Tên");
            #endregion     


            CbPaperStyle.SelectedIndex = 1;
            CbDonVi.SelectedIndex = 0;
            for (int i = 0; i < RowsPerPage * ColsPerPage; i++)
            {
                CbStartAt.Items.Add(i);
                
            }
            CbStartAt.SelectedIndex = 0;

            numSoLuongIn.Value = 1;
            DgrInHang.ColumnCount = 5;
        }

        private void TxtBarCode_TextChanged(object sender, EventArgs e)
        {
            MyBarCode.Text = TxtBarCode.Text;
            PtrBarCode.Text = TxtBarCode.Text;
        }
       
        private void DgrHangHoa_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            TxtBarCode.Text = DgrHangHoa["Ma", DgrHangHoa.CurrentRow.Index].Value.ToString();
            TxtBookName.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString();
            TxtTopText.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString();        
            TxtBottomText.Text = string.Format("{0:0,0}", Decimal.Parse((DgrHangHoa["GiaBia", DgrHangHoa.CurrentRow.Index].Value.ToString())));
            LbBottom.Text = "Giá: " + string.Format("{0:0,0}", Decimal.Parse((DgrHangHoa["GiaBia", DgrHangHoa.CurrentRow.Index].Value.ToString()))); 
            if(DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString().Length>50)
            {
                LbTop.Text = DgrHangHoa["Ten", DgrHangHoa.CurrentRow.Index].Value.ToString().Substring(0, 50);  
            }
            if (RdoToanBoKhoHang.Checked == true)
            {
                numSoLuongIn.Value = 1;
            }
            else
            {
                numSoLuongIn.Value = (decimal)DgrHangHoa[3, DgrHangHoa.CurrentRow.Index].Value;
            }          
        }

        private void RdoToanBoKhoHang_CheckedChanged(object sender, EventArgs e)
        {
            if (RdoToanBoKhoHang.Checked)
            {
                DanhMucVatTuHangHoa.Instance.DataView.Table.DefaultView.Sort = "Ten";
                DgrHangHoa.DataSource = Lists.DanhMucVatTuHangHoa.Instance.DataView;
                TxtFindName.Focus();
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bìa";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                for (int c = 0; c < DgrHangHoa.ColumnCount; c++)
                {
                    if ((DgrHangHoa.Columns[c].Name == "Ma") || (DgrHangHoa.Columns[c].Name == "Ten") || (DgrHangHoa.Columns[c].Name == "GiaBia"))
                    {
                        DgrHangHoa.Columns[c].Visible = true;
                    }
                    else
                    {
                        DgrHangHoa.Columns[c].Visible = false;
                    }
                }

                cmbDoiTuong.Enabled = true;
                dtNgayHoaDon.Enabled = false;
                cmbPhieuNhap.Enabled = false;
            }
            else
            {
                cmbDoiTuong.Enabled = false;
                dtNgayHoaDon.Enabled = true;
                cmbPhieuNhap.Enabled = true;
            }
        }

        private void RdoTheoPhieuNhap_CheckedChanged(object sender, EventArgs e)
        {
            if (RdoTheoPhieuNhap.Checked)
                SearhTheoHoaDon();            
        }

        private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
        {
            if(RdoTheoPhieuNhap.Checked)
                SearhTheoHoaDon();
        }

        private void SearhTheoHoaDon()
        {
            FrmProgressBar.StartShowProgress();
            try
            {
                DieuKienTimKiemChungTu dkTimKiem = new DieuKienTimKiemChungTu();
                DateTime today = dtNgayHoaDon.Value;
                dkTimKiem.TuNgay = new NullableDate(new DateTime(today.Year, today.Month, today.Day, 0, 0, 0));
                dkTimKiem.DenNgay = new NullableDate(new DateTime(today.Year, today.Month, today.Day, 23, 59, 59));
                dkTimKiem.LoaiChungTu = DanhMucLoaiChungTu.Instance.GetByMa("HoaDonMuaHang");
                DanhSachChungTu dsHoaDonMua = new DanhSachChungTu();
                dsHoaDonMua.LoadFromDB(dkTimKiem.BuildSqlStatement(1000, 1));
                cmbPhieuNhap.DataSource = dsHoaDonMua.DataTable;
                cmbPhieuNhap.DisplayMember = "So";
                cmbPhieuNhap.ValueMember = "ChungTuID";
            }
            catch (Exception ex)
            {
            }
            FrmProgressBar.FinishShowProgress();
        }

        private void BtPrint_Click(object sender, EventArgs e)
        {
            
            try {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;

                    int index = 0;

                    //MyBarCode.Width = 800;
                    //MyBarCode.Refresh();

                    for (int r = 0; r < DgrInHang.RowCount-1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = (DgrInHang[1, r].Value).ToString();
                        if (strTen.Length > 22)
                        {
                            strTen=strTen.Substring(0,19)+"...";
                        }
                      
                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            MyBarCode.Text = (string)(DgrInHang[0, r].Value);
                            MyBarCode.Refresh();
                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            MyBarCode.Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);


                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;
                            switch (index)
                            {
                                case 1:
                                   
                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"]=((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"]=((DgrInHang[4, r].Value.ToString()));
                                    break;

                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"]=((DgrInHang[4, r].Value.ToString()));
                                    //index = 0;
                                    break;
                                case 4:

                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;

                                case 6:
                                    row["Image6"] = ms.ToArray();
                                    row["Ten6"] = strTen;
                                    row["Gia6"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai6"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                            }
                        }
                    }


                    RptBarcode report = new RptBarcode();
                    report.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void CbPaperStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            switch (CbPaperStyle.SelectedIndex)
            {
                case 0:
                    {
                        cPrinterWidth = 106 * 56.7; //' 106 mm (x 56.7 twip)
                        cPrinterHeight = (73 * 56.7); //'4479 '79 mm
                        break;
                    }
                case 1:
                    {
                        cPrinterWidth = 6067;//' 107 mm (x 56.7 twip)
                        cPrinterHeight = 5670; //'100 mm
                        break;
                    }
                case 2:
                    {
                        cPrinterWidth = 5953; //' 105 mm (x 56.7 twip)
                        cPrinterHeight = 8788; //'155 mm
                        break;
                    }
                case 3:
                    {
                        cPrinterWidth = 11907;//' = 210 mm
                        cPrinterHeight = 16840;// '297 mm
                        break;
                    }              
            }
            //CbX.SelectedIndex = Convert.ToInt32(cPrinterWidth / MyBarCode.Width - 1);  
            CbX.SelectedIndex = Convert.ToInt32((int)cPrinterWidth /(int)1815 )-1;           
             //CbY.SelectedIndex = Convert.ToInt32(cPrinterHeight / (LbBottom.Top + LbBottom.Height - LbTop.Top) - 1);
            CbY.SelectedIndex = Convert.ToInt32((int)(cPrinterHeight) / (int)(1155))-1 ;
             ColsPerPage = CbX.SelectedIndex+1 ;
             RowsPerPage = CbY.SelectedIndex+1 ;
        }

        private void CbY_SelectedIndexChanged(object sender, EventArgs e)
        {
            RowsPerPage = CbY.SelectedIndex + 1;
        }

        private void CbX_SelectedIndexChanged(object sender, EventArgs e)
        {
            ColsPerPage = CbX.SelectedIndex + 1;
        }
       
        private void BtDelete_Click(object sender, EventArgs e)
        {
            foreach (DataGridViewRow r in DgrInHang.SelectedRows)
            {
                if (r.Index !=DgrInHang.RowCount-1)
                {
                    DgrInHang.Rows.RemoveAt(r.Index);
                }               
            }
        }

        private void DgrInHang_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (DgrInHang.CurrentRow.Index != DgrInHang.RowCount-1)
            {
                try {
                    TxtBarCode.Text = DgrInHang[0, DgrInHang.CurrentRow.Index].Value.ToString();
                    TxtBookName.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                    TxtTopText.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                    TxtBottomText.Text = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, DgrInHang.CurrentRow.Index].Value.ToString())));
                    LbBottom.Text = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, DgrInHang.CurrentRow.Index].Value.ToString())));
                    LbTop.Text = DgrInHang[1, DgrInHang.CurrentRow.Index].Value.ToString();
                    if (numSoLuongIn.Text == "")
                    {
                        numSoLuongIn.Value = 1;
                    }
                    else
                    {
                        numSoLuongIn.Value =  (int)DgrInHang[3, DgrInHang.CurrentRow.Index].Value;
                    }
                }
                catch (Exception ex)
                { }
            }
        }

        private void BtExit_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            FrmProgressBar.StartShowProgress();
            SqlConnection con = new SqlConnection(AccountingLibs.LocalSettings.ConnectString);
            try
            {
                con.Open();
                SqlCommand cmd = con.CreateCommand();
                cmd.CommandText = string.Format("SELECT B.Ma, B.Ten, B.GiaBia, A.Value1 AS SoLuong, C.DoiTuongNghiepVu1ID\n" +
                          " FROM KhoanMucChungTu A INNER JOIN VatTuHangHoa B ON A.VatTuHangHoa1ID = B.ID INNER JOIN ChungTu C ON A.ChungTuID = C.ChungTuID \n" +
                           "  WHERE A.ChungTuID IN( \n" +
                           " SELECT ChungTuID " +
                           "FROM ChungTu \n" +
                           "WHERE ChungTuGocID = '{0}')",
                           cmbPhieuNhap.SelectedValue
                           );
               
                SqlDataAdapter da = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                da.Fill(ds);
                DgrHangHoa.DataSource = ds.Tables[0].DefaultView;
                DgrHangHoa.Columns["GiaBia"].HeaderText = "Giá bìa";
                DgrHangHoa.Columns["GiaBia"].DefaultCellStyle.Format = "0";
                DgrHangHoa.Columns["Ma"].HeaderText = "Mã";
                DgrHangHoa.Columns["Ten"].HeaderText = "Tên";
                DgrHangHoa.Columns["SoLuong"].HeaderText = "Số lượng";
                DgrHangHoa.Columns["SoLuong"].DefaultCellStyle.Format = "0";

                cmd.CommandText = string.Format("SELECT DoiTuongNghiepVu1ID " +
                                                "FROM ChungTu " +
                                                "WHERE ChungTuID = '{0}'",
                                                cmbPhieuNhap.SelectedValue);
                SqlDataReader dr = cmd.ExecuteReader();
                if (dr.Read())
                {
                    cmbDoiTuong.EditValue = (int)dr["DoiTuongNghiepVu1ID"];
                }
                dr.Close();
            }
            catch (Exception ex)
            {
            }
            finally
            {
                con.Close();
            }
            FrmProgressBar.FinishShowProgress();
        }

        private void BtEdit_Click(object sender, EventArgs e)
        {
            DgrInHang[3, DgrInHang.CurrentRow.Index].Value = numSoLuongIn.Value;
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void TxtFindName_TextChanged(object sender, EventArgs e)
        {
            try
            {
                DataTable tb = DanhMucVatTuHangHoa.Instance.DataView.Table;
                tb.DefaultView.Sort = "Ten";                
                tb.DefaultView.RowFilter = "Ten like '%" + TxtFindName.Text +"%'";              
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void DgrHangHoa_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (cmbDoiTuong.EditValue == null)
            {
                MessageBox.Show("Bạn chưa chọn nhà cung cấp mặt hàng");
                cmbDoiTuong.Focus();
            }
            else
            {
                if (RdoTheoPhieuNhap.Checked)
                {
                    foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                    {
                        DgrInHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, DgrHangHoa["SoLuong", r.Index].Value,
                                            DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                    }
                }
                else
                {
                    foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                    {
                        DgrInHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, numSoLuongIn.Value,
                                            DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                    }
                }
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                //DgrInHang.ColumnCount = 5;
                if (cmbDoiTuong.EditValue == null)
                {
                    MessageBox.Show("Bạn chưa chọn nhà cung cấp mặt hàng");
                    cmbDoiTuong.Focus();
                }
                else
                {
                    if (RdoTheoPhieuNhap.Checked)
                    {
                        foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                        {
                            DgrInHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, DgrHangHoa["SoLuong", r.Index].Value,
                                                DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                        }
                    }
                    else
                    {
                        foreach (DataGridViewRow r in DgrHangHoa.SelectedRows)
                        {
                            DgrInHang.Rows.Add(DgrHangHoa["Ma", r.Index].Value, DgrHangHoa["Ten", r.Index].Value, DgrHangHoa["GiaBia", r.Index].Value, numSoLuongIn.Value,
                                                DanhMucDoiTuongNghiepVu.Instance.GetByID((Guid)cmbDoiTuong.EditValue).Ma);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }
        private void PrintA5()
        {
            try
            {
                if (DgrInHang.RowCount == 0)
                {
                    MessageBox.Show("Bạn chưa chọn mặt hàng để in mã vạch");
                }
                else
                {
                    DsPrintBarCode ds = new DsPrintBarCode();
                    DataRow row = null;

                    int index = 0;

                    //MyBarCode.Width = 800;
                    //MyBarCode.Refresh();

                    for (int r = 0; r < DgrInHang.RowCount - 1; r++)//moi loai tem
                    {
                        int soLuong = Convert.ToInt32(DgrInHang[3, r].Value);
                        string strTen = (DgrInHang[1, r].Value).ToString();
                        if (strTen.Length > 22)
                        {
                            strTen = strTen.Substring(0, 19) + "...";
                        }

                        for (int c = 0; c < soLuong; c++)//moi tem cua mot loai
                        {
                            MyBarCode.Text = (string)(DgrInHang[0, r].Value);
                            MyBarCode.Refresh();
                            System.IO.MemoryStream ms = new System.IO.MemoryStream();
                            MyBarCode.Picture.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);


                            if (index == 0)
                            {
                                row = ds.DataTable1.NewRow();
                                ds.DataTable1.Rows.Add(row);
                            }
                            index++;
                            switch (index)
                            {
                                case 1:

                                    row["Image1"] = ms.ToArray();
                                    row["Ten1"] = strTen;
                                    row["Gia1"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai1"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 2:
                                    row["Image2"] = ms.ToArray();
                                    row["Ten2"] = strTen;
                                    row["Gia2"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai2"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;

                                case 3:
                                    row["Image3"] = ms.ToArray();
                                    row["Ten3"] = strTen;
                                    row["Gia3"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai3"] = ((DgrInHang[4, r].Value.ToString()));
                                    //index = 0;
                                    break;
                                case 4:

                                    row["Image4"] = ms.ToArray();
                                    row["Ten4"] = strTen;
                                    row["Gia4"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai4"] = ((DgrInHang[4, r].Value.ToString()));
                                    break;
                                case 5:
                                    row["Image5"] = ms.ToArray();
                                    row["Ten5"] = strTen;
                                    row["Gia5"] = string.Format("{0:0,0}", Decimal.Parse((DgrInHang[2, r].Value.ToString()))) + " đ";
                                    row["ChungLoai5"] = ((DgrInHang[4, r].Value.ToString()));
                                    index = 0;
                                    break;
                               
                            }
                        }
                    }


                    RptA5BarCode report2 = new RptA5BarCode();
                    report2.SetDataSource(ds);

                    FrmShowReport frm = new FrmShowReport();
                    frm.crystalReportViewer1.ReportSource = report2;
                    frm.Show();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        
        }

        private void button1_Click(object sender, EventArgs e)
        {
            PrintA5();
        }
    }
}

